from django.http import HttpResponse
from django.shortcuts import redirect
from django.conf import settings

class RequestInfoMiddleware:
    """中间件：输出请求头信息、验证登录状态、记录IP地址"""
    
    def __init__(self, get_response):
        self.get_response = get_response
        
    def __call__(self, request):
        # 1. 输出请求头信息
        self._log_request_headers(request)
        
        # 2. 验证用户登录状态
        if not self._check_user_authenticated(request):
            return redirect(settings.LOGIN_URL)
            
        # 3. 输出客户端IP地址
        client_ip = self._get_client_ip(request)
        print(f"客户端IP: {client_ip}")
        
        # 继续处理请求
        response = self.get_response(request)
        return response
    
    def _log_request_headers(self, request):
        """记录并输出请求头信息"""
        print("\n===== 请求头信息 =====")
        for header, value in request.META.items():
            if header.startswith('HTTP_'):
                # 转换HTTP_CONTENT_TYPE -> Content-Type
                header_name = header[5:].replace('_', '-').title()
                print(f"{header_name}: {value}")
        print("====================\n")
    
    def _check_user_authenticated(self, request):
        """验证用户是否已登录（排除白名单路径）"""
        # 设置无需登录的URL白名单
        login_exempt_urls = [
            settings.LOGIN_URL,
            '/api/public/',  # 示例公共API路径
        ]
        
        # 检查当前路径是否需要验证
        if any(url in request.path for url in login_exempt_urls):
            return True
            
        # 验证用户登录状态
        return request.user.is_authenticated
    
    def _get_client_ip(self, request):
        """获取客户端真实IP地址"""
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            return x_forwarded_for.split(',')[0]
        return request.META.get('REMOTE_ADDR')    